// 引入获取数据方法

import {
    cartCount
} from '../api/cart.js'



import { getBaseSetting, getBaseTab } from 'api/common/common.js'

//积分规则的名字
import { getRule } from "api/pointsApi";

import { bindDistri } from 'api/extensionApi'

import {
    CART_NUM,
    THEMES,
    BOTTOMCOLUMN,
    INTEGRALNAME,
    ACCOUNT_MESSAGE
} from './mutation-types'

import { getUrlKey } from 'utils/utils';

import config from 'config/config';

import oauthApi from 'api/login'

import { debounce } from 'utils/utils'

// 请求购物车数据
export default {
    async getCartGoods({ commit }) {
        const res = await cartCount()
        if (res.success) {
            commit(CART_NUM, { cartNum: res.result })
        }
    },

    async loadRule({ commit }) {
        const res = await getRule()
        if (res.success) {
            commit(INTEGRALNAME, { integralName: res.result ? res.result.integralName : '积分' })
        }
    },
	
	getBaseSetting({commit, state, dispatch}){
		return new Promise((resolve, reject) => {
			dispatch('__getBaseSetting',resolve, reject)
		})
	},
	__getBaseSetting:debounce(({commit}, resolve, reject)=>{
		
		let parmes = {};
		
		getBaseTab().then(res => {
		    console.log("请求装修信息结果：", res);
		
		
		
		    if (res.status != 1) {
		        return;
		    }
		
		    if (!res.result) {
		        return;
		    }
		
		    parmes = res.result;
		
		    parmes.theme = res.result.name
		    parmes.color = res.result.color
			console.log(parmes)
		    commit(THEMES, { themes: parmes })
		
		    let wxStatus = parmes.enableWeixinLogin
		    if (wxStatus != undefined) {
		        commit('SET_EnableWeixinLogin', parmes.enableWeixinLogin)
		    }
		
		
		
		
		    //过滤重组
		    let tabParame = JSON.parse(JSON.stringify(res.result))
		    let newTabParame = {
		        background: tabParame.tabBarSetting.background,
		        displayText: tabParame.tabBarSetting.displayText,
		        pages: tabParame.tabBarSetting.pages,
		        tabBar: []
		    }
		
		    let result = [];
		    for (let index = 0; index < tabParame.tabBarSetting.tabBar.list.length; index++) {
		        const element = tabParame.tabBarSetting.tabBar.list[index];
		 
		        // 每循环一次创建一个对象
		        let obj = {};
		        // 利用自执行函数，解决闭包问题
		        (function (index) {
		            obj.text = element.text;
		            obj.iconPath = element.iconPath ? config.photoServer + element.iconPath : require(`@/assets/style-images/${element.defaultIconPath}`)
		            obj.selectedIconPath = element.selectedIconPath ? config.photoServer + element.selectedIconPath : require(`@/assets/style-images/${element.defaultSelectedIconPath}-${parmes.theme}.png`)
		            obj.path = _method.filtrMethod(element.action)
		            result.push(obj)
		        }(index))
		
		    }
		
		
		    newTabParame.tabBar = result
		    commit(BOTTOMCOLUMN, { bottomColumn: newTabParame })
		
			resolve(res)
		}).catch(e => {
			reject(err)
		    console.error(e);
		})
	}, 100),
	
    //请求装修信息
 //    async getBaseSetting({ commit, state }) {
 //        let parmes = { theme: 'green', color: '#4eae31' };

 //        await getBaseTab().then(res => {
 //            console.log("请求装修信息结果：", res);



 //            if (res.status != 1) {
 //                return;
 //            }

 //            if (!res.result) {
 //                return;
 //            }

 //            parmes = res.result;

 //            parmes.theme = res.result.name
 //            parmes.color = res.result.color
	// 		console.log(parmes)
 //            commit(THEMES, { themes: parmes })

 //            let wxStatus = parmes.enableWeixinLogin
 //            if (wxStatus != undefined) {
 //                commit('SET_EnableWeixinLogin', parmes.enableWeixinLogin)
 //            }




 //            //过滤重组
 //            let tabParame = JSON.parse(JSON.stringify(res.result))
 //            let newTabParame = {
 //                background: tabParame.tabBarSetting.background,
 //                displayText: tabParame.tabBarSetting.displayText,
 //                pages: tabParame.tabBarSetting.pages,
 //                tabBar: []
 //            }

 //            let result = [];
 //            for (let index = 0; index < tabParame.tabBarSetting.tabBar.list.length; index++) {
 //                const element = tabParame.tabBarSetting.tabBar.list[index];
 
 //                // 每循环一次创建一个对象
 //                let obj = {};
 //                // 利用自执行函数，解决闭包问题
 //                (function (index) {
 //                    obj.text = element.text;
 //                    obj.iconPath = element.iconPath ? config.photoServer + element.iconPath : require(`@/assets/style-images/${element.defaultIconPath}`)
 //                    obj.selectedIconPath = element.selectedIconPath ? config.photoServer + element.selectedIconPath : require(`@/assets/style-images/${element.defaultSelectedIconPath}-${parmes.theme}.png`)
 //                    obj.path = _method.filtrMethod(element.action)
 //                    result.push(obj)
 //                }(index))

 //            }


 //            newTabParame.tabBar = result
 //            commit(BOTTOMCOLUMN, { bottomColumn: newTabParame })


 //        }).catch(e => {
 //            console.error(e);
 //        })
 //    },

    setAccountMessage({ commit }, accountMessage) {
        commit(ACCOUNT_MESSAGE, { accountMessage });
    },
	// 异步等待拿到门店标题
	waitTitle({commit,state}) {
		return new Promise((resolve, reject) => {
			 let interval = setInterval(() => {
				if (state.themes && state.themes.shopName) {
					resolve(state.themes)
					clearInterval(interval)
				}
			},10)
		})
	},
	setDistribution({commit,state}) {
		if(getUrlKey('invitCode')) {
			let invitCode = getUrlKey('invitCode');
			// commit(setInvitCode, { invitCode });
			bindDistri({ invitationCode: invitCode }).then((res) => {
			})
		}
	},
	async setupInfo({commit,state}) {
		const res = await oauthApi.needSetupInfo()
		state.curUpInfo = res
	}


    //底部栏数据
    // async getBaseTab({commit}) {
    //     let parmes = {}
    //     return await getBaseTab().then(res => {


    //         if (res.status == 1) {
    //             parmes = res.result
    //         }


    //         // parmes = res.result;

    //         // parmes.theme = res.result.name
    //         // parmes.color = res.result.color
    //         commit(BOTTOMCOLUMN, {bottomColumn: parmes}) 

    //     }).catch( e =>{
    //         console.error(e);
    //     })

    // }
}



const _method = {
    filtrMethod(parmes) {
        let path = " ";

        if (parmes.type == "prodDetail") {
            //去商品详情
            path = `/goodsDetail?goodsInfoId=${parmes.target}`
        } else if (parmes.type == "prodGroup") {
            //商品分组
            path = `/search/prodGroupList?prodGroupId=${parmes.target}&name=${parmes.name}`
        } else if (parmes.type == "prodList") {
            path = `/searchList?grade=${parmes.grade}&categoryId=${parmes.target}&source=${parmes.subType}`
        } else if (parmes.type == 'marketing') {
            //营销活动
            let target = parmes.target
            if (target == 'fight') {
                path = `/pages/fight/fight`
            }
        } else if (parmes.type == 'method') {
            //常用功能
            let target = parmes.target
            switch (target) {
                case "home":
                    path = "/index";
                    break;
                case "shopCart":
                    path = "/cart";
                    break;
                case "category":
                    path = "/category";
                    break;
                case "myCoupons":
                    path = "/myCoupon";
                    break;
                case "myMsg":
                    path = "/message";
                    break;
                case "myFavourite":
                    path = "/collection";
                    break;
                case "userCenter":
                    path = "/my";
                    break;
            }
        } else if (parmes.type == 'url') {
            //自定义url
            path = parmes.target
        } else if (parmes.type == 'page') {
            path = `/webpage?pageId=${parmes.target}&title=${parmes.name}`
        }

        return path
    }
}